<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/10/14
 * Time: 10:31
 */

namespace ticket\libs;


use ticket\modules\frontend\models\CouponLog;
use ticket\modules\frontend\models\KlyChannel;
use yii\base\Exception;
use yii\log\FileTarget;
use Yii;


class Communal
{

    /*** 核销优惠券
     * @param $post
     * @param $orderSn
     * @param $member_id
     * @param $ticketInfo
     * @param $oid
     * @return float|int
     */
    public function verifyCoupon($post,$orderSn,$member_id,$ticketInfo,$oid)
    {
        if  ($post['is_coupon'] == 1){   // 使用了优惠券
            $result = $this->sendCoupon($post['appId'],$post,$orderSn,$member_id);
            if (!$result){
                throw new Exception('优惠券核销失败',10506);
            }
            if ($post['coupons_type'] == 1){         // 折扣券
                $real_price = $ticketInfo['total_price'] * ($post['discount']/100);
            }elseif ($post['coupons_type'] == 2){    // 现金券
                $real_price =  $ticketInfo['total_price'] - $post['discount'];
            }else{                                  // 满减券
                $real_price =  $ticketInfo['total_price'] - $post['discount'];
            }
            $discount = $ticketInfo['total_price'] - $real_price;
            CouponLog::addInfo($oid,$discount,$post,'success',$member_id,$post['coupon_from']);
        }elseif($post['is_coupon'] == 2 and $post['coupon_from'] == 3){  // 年卡折扣

            if ($post['coupons_type'] == 1){         // 折扣券
                $real_price = $ticketInfo['total_price'] * ($post['discount']/100);
            }elseif ($post['coupons_type'] == 2){    // 现金券
                $real_price =  $ticketInfo['total_price'] - $post['discount'];
            }else{                                  // 满减券
                $real_price =  $ticketInfo['total_price'] - $post['discount'];
            }
            $discount = $ticketInfo['total_price'] - $real_price;
            CouponLog::addInfo($oid,$discount,$post,'success',$member_id,$post['coupon_from']);
        }else{
            $real_price = $ticketInfo['total_price'];
        }
		
		if($post['isvip']==1){
			$real_price = $ticketInfo['total_price'];
		}

        return $real_price;

    }





    /*** 核销优惠券
     * @param $appId            appId
     * @param $params           post 参数
     * @param $orderSn          订单号
     * @return bool
     */
    public function sendCoupon($appId,$params,$orderSn,$member_id)
    {
        if ($params['coupon_from'] == 1){            // 恐龙园优惠券核销
            $url = 'https://jqxcx.klygf.com/ClubMemberSystem/inteface/coupon/verify.json';      // 恐龙园优惠券核销接口
            $channel = isset($params['channel'])?$params['channel']:'onlineTicket';
            $key = $this->couponKey($channel);
            $paramsData = [// 'onlineTicket'
                'channel' => $channel,
                'memberId' => $params['member_id'],
                'couponid' => $params['coupon_id'],
                'couponname' => $params['coupon_name'],
                'orderId' => $orderSn,
                'sign' => md5($key.date("Ym")),
            ];
            $res = json_decode(Curl::post($url,$paramsData),true);
            if ($res['code'] == '00'){
                return true;
            }else{
                $this->recordText(99999,'优惠券核销失败'.json_encode($paramsData,JSON_UNESCAPED_UNICODE),json_encode($res,JSON_UNESCAPED_UNICODE));
                return false;
            }
        }elseif ($params['coupon_from'] == 2){          // 其他优惠券核销
            $url = Yii::$app->params['Coupon_Url'].'/member/coupon/use-coupon';
            $paramsData = [
                'appid' => $appId,
                'member_id' => $member_id,
                'code' => $params['couponCode'],
                'secretkey' => 'j5pAPD7dXFPfhky9ASTfBuKomcTK8qzN',
                'useremark' => '票务-门票',
            ];
            $res = json_decode(Curl::post($url,$paramsData),true);
            if ($res['code'] !== '0'){
                return true;
            }else{

                $this->recordText(99999,'优惠券核销失败'.json_encode($paramsData,JSON_UNESCAPED_UNICODE),json_encode($res,JSON_UNESCAPED_UNICODE));
                return false;
            }
        }else{
            return false;
        }

    }





    protected function recordText($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/coupon/use_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }


    private function couponKey($channel)
    {
        $key = KlyChannel::find()->where(['channel' => $channel])->select(['key'])->one()->key;
        return $key;
    }
    
    
    
}